<template>
	<el-dialog v-model="dialogVisible" :title="parameter.title" :destroy-on-close="true" draggable width="500px">
		<el-upload
			action="#"
			class="upload"
			:drag="true"
			:limit="parameter.limit"
			:multiple="true"
			:show-file-list="false"
			:http-request="uploadFile"
			:before-upload="beforeFileUpload"
			:on-exceed="handleExceed"
			:on-success="fileUploadSuccess"
			:on-error="fileUploadError"
			:accept="parameter.fileTypes.join(',')"
		>
			<slot name="empty">
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			</slot>
			<template #tip>
				<slot name="tip">
					<div class="el-upload__tip">请上传 .xls , .xlsx 标准格式文件，文件最大为 {{ parameter.fileSize }}M</div>
				</slot>
			</template>
		</el-upload>
	</el-dialog>
</template>
<script setup lang="ts" name="ImportFile">
import { ref } from "vue";
import { ElNotification, UploadRequestOptions, UploadRawFile } from "element-plus";

interface FileParameterProps {
	title: string; // 标题
	fileSize?: number; // 文件大小
	fileTypes: string[]; // 文件类型
	limit?: number; // 上传文件数量
	importApi?: (params: any) => Promise<any>; // 批量导入的Api
}

// 父组件传递过来的参数
const parameter = ref<FileParameterProps>({
	title: "",
	limit: 1,
	fileSize: 5,
	fileTypes: [
		"application/vnd.ms-excel",
		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		"application/msword"
	]
});
const acceptParams = (params: FileParameterProps) => {
	parameter.value = { ...parameter.value, ...params };

	dialogVisible.value = true;
};

const dialogVisible = ref(false);

const uploadFile = async (param: UploadRequestOptions) => {
	let formData = new FormData();
	formData.append("file", param.file);
	await parameter.value.importApi!(formData);
	dialogVisible.value = false;
};

// 上传文件之前判断
const beforeFileUpload = async (file: UploadRawFile) => {
	const isFile = parameter.value.fileTypes!.includes(file.type as File.FileMimeType);
	if (!isFile) {
		ElNotification({
			title: "温馨提示",
			message: "上传文件格式错误！",
			type: "warning"
		});
	}
	const fileSize = file.size / 1024 / 1024 < parameter.value.fileSize!;
	if (!fileSize) {
		ElNotification({
			title: "温馨提示",
			message: `上传文件大小不能超过${parameter.value.fileSize}MB！`,
			type: "warning"
		});
	}
	return isFile && fileSize;
};

// 文件超出提示
const handleExceed = async () => {
	ElNotification({
		title: "温馨提示",
		message: `最多只能上传${parameter.value.limit}个文件！`,
		type: "warning"
	});
};

const fileUploadSuccess = async () => {
	ElNotification({
		title: "温馨提示",
		message: `上传成功！`,
		type: "success"
	});
};

const fileUploadError = async () => {
	ElNotification({
		title: "温馨提示",
		message: `上传失败，请您重新上传！`,
		type: "error"
	});
};

defineExpose({
	acceptParams
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>